import { OnInit, Component, ViewChild, Output, EventEmitter } from '@angular/core';
import { NotificationInformationService } from 'src/app/project/service/icm/icm-student-academic/notification-information/notification-information.service';
import { FormBuilder, Validators, FormGroup, NgForm } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { NotificationInformationDTO } from 'src/app/project/model/icm/icm-student-academic/notification-information/notification-information.dto';
import { FormUtil } from '@shared/utils/form-util';
import { SystemFileDTO } from 'src/app/project/model/icm/icm-global/system-file/system-file-dto';
import { AttachSmallComponent } from '@shared/common-component/attach-small.component';
import { format } from 'date-fns';

@Component({
  selector: 'app-notification-information-detail',
  templateUrl: './notification-information-detail.component.html',
  styles: [],
})
export class NotificationInformationDetailComponent implements OnInit {
  constructor(
    private notificationInformationService: NotificationInformationService,
    private fb: FormBuilder,
    private msg: NzMessageService,
    private modalService: NzModalService,
  ) {
    this.validateForm = this.fb.group({
      title: ['', [Validators.required]],
      type: ['', [Validators.required]],
      content: ['', [Validators.required]],
    });
  }

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 附件
   */
  @ViewChild('attachSmallComponent', { static: false })
  attachSmallComponent: AttachSmallComponent;

  /**
   * 附件是否只读
   */
  isReview: boolean;

  /**
   * 附件组件按钮可见性
   */
  isShow: boolean;
  /**
   * 文件类型
   */
  fileType: string;

  /**
   * 附件数据
   */
  attachFiles: SystemFileDTO[];

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<NotificationInformationDTO>>();

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 配置名称是否已存在，true为已存在
   */
  isExist: boolean;

  /**
   * 通知类型
   */
  notificationInformationDTO: NotificationInformationDTO = {
    id: null,
    title: null,
    type: null,
    isConfirm: false,
    content: null,
    receiverId: null,
    receiverName: null,
    date: null,
  };

  isConfirm = false;
  /**
   * 编辑/预览
   */
  preview() {
    // 编辑状态下isPreView为false，isReView为true
    this.isPreView = !this.isPreView;
  }

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 修改或新增配置信息
   * @param isPreView 是否预览
   * @param item 配置信息
   */
  edit(isPreView: boolean, item: NotificationInformationDTO, isConfirm?: boolean) {
    this.isPreView = isPreView;
    this.isConfirm = isConfirm ? isConfirm : false;
    this.notificationInformationDTO = this.initConfiguration(item);
    this.isVisible = true;
  }

  /**
   * 新建通知
   * @param receiverId 通知对象id
   * @param receiverName 通知对象名称
   */
  create(receiverId: string, receiverName: string) {
    this.isPreView = false;
    this.notificationInformationDTO = this.initConfiguration(null);
    this.notificationInformationDTO.receiverId = receiverId;
    this.notificationInformationDTO.receiverName = receiverName;
    this.isVisible = true;
  }

  /**
   * 初始化全局配置信息
   */
  initConfiguration(item: NotificationInformationDTO): NotificationInformationDTO {
    return {
      id: item ? item.id : null,
      type: item ? item.type : null,
      title: item ? item.title : null,
      content: item ? item.content : null,
      receiverId: item ? item.receiverId : null,
      isConfirm: item ? item.isConfirm : false,
      receiverName: item ? item.receiverName : null,
      fileIds: item ? item.fileIds : [],
      files: item ? item.files : null,
      date: item ? item.date : format(new Date().toString(), 'YYYY-MM-DD'),
    };
  }

  /**
   * 上传思想分附件
   */
  uploadAttach(fileType: string, files?: SystemFileDTO[]) {
    this.fileType = fileType;
    this.attachFiles = files;
    this.attachSmallComponent.isVisible = true;
    this.isReview = this.isPreView;
    this.isShow = !this.isPreView;
  }

  /**
   * 将附件弹射回detail
   */
  resultChange(files: SystemFileDTO[]) {
    this.notificationInformationDTO.files = files;
    this.notificationInformationDTO.fileIds = [];
    this.notificationInformationDTO.files.forEach(file => {
      this.notificationInformationDTO.fileIds.push(file.id);
    });
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.notificationInformationDTO.title === '') {
      this.msg.error('通知标题必填');
      return false;
    }
    if (this.notificationInformationDTO.type === '') {
      this.msg.error('通知类型必填');
      return false;
    }
    return true;
  }

  /**
   * 改变通知状态为已读
   */
  complite() {
    this.modalService.confirm({
      nzTitle: '是否确认已读',
      nzContent: `<p>确认为已读</p>`,
      nzOnOk: () => {
        this.notificationInformationService.complete(this.notificationInformationDTO.id).subscribe(data => {
          if (data) {
            this.msg.success('已确认');
            this.handleCancel();
          }
        });
      },
    });
  }
  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.notificationInformationDTO.id) {
      // id为空，新建配置信息
      // tslint:disable-next-line: deprecation
      this.notificationInformationService.create(this.notificationInformationDTO).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        null,
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，修改保存配置信息
      // tslint:disable-next-line: deprecation
      this.notificationInformationService.complete(this.notificationInformationDTO.id).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        null,
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: NotificationInformationDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }
  ngOnInit() {}
}
